//
//  NDTrackingTool.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/11/3.
//

import AppTrackingTransparency
import AdSupport

final class NDTrackingTool {
    
    static let shared = NDTrackingTool()
    private init() {}
    
    // MARK: - Public Methods
    
    /// 请求广告追踪权限并返回 IDFA
    func requestIDFA(completion: @escaping (String?) -> Void) {
        ATTrackingManager.requestTrackingAuthorization { status in
            DispatchQueue.main.async {
                completion(self.handleiOS14Authorization(status))
            }
        }
    }
    
    /// 获取当前可用的 IDFA（不触发权限弹窗）
    var currentIDFA: String? {
        return isAuthorized ? advertisingIdentifier : nil
    }
    
    /// 检查广告追踪权限状态
    var isAuthorized: Bool {
        if #available(iOS 14, *) {
            return ATTrackingManager.trackingAuthorizationStatus == .authorized
        } else {
            return ASIdentifierManager.shared().isAdvertisingTrackingEnabled
        }
    }
    
    /// 获取当前授权状态描述
    var authorizationStatus: ATTrackingManager.AuthorizationStatus {
        return ATTrackingManager.trackingAuthorizationStatus
    }
    
    // MARK: - Private Methods
    
    /// 处理 iOS 14+ 授权状态
    private func handleiOS14Authorization(_ status: ATTrackingManager.AuthorizationStatus) -> String? {
        switch status {
        case .authorized:
            return advertisingIdentifier
        case .denied, .restricted, .notDetermined:
            return nil
        @unknown default:
            return nil
        }
    }

    /// 获取广告标识符（不检查权限）
    private var advertisingIdentifier: String {
        return ASIdentifierManager.shared().advertisingIdentifier.uuidString
    }
}

